package com.topcent.tioxyc.consumer;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.InvoiceDocument;
import com.topcent.tioxyc.pojo.PurchaseOrder;
import com.topcent.tioxyc.pojo.PurchaseRequest;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2024/11/26 14:08
 * @Description: 采购申请单消费类】
 */
@Component
@RabbitListener(queues = "PurchaseRequest")
@Slf4j
public class PurchaseRequestConsumer {
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 处理 payload 消息
            //System.out.println("Received payload: " + msg);
            // 在这里执行具体的业务逻辑

            // 在这里处理推送来的数据
            JSONObject payloadJSON = JSONUtil.parseObj(msg);
            String op = payloadJSON.getStr("op");
            String data = payloadJSON.getStr("data");

            if (DATA_CREATE.equals(op)) {
                create(data);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }

    private void create(String data) {
        PurchaseRequest purchaseRequest = JSONUtil.toBean(data, PurchaseRequest.class);
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterCxv = new HashMap<>();
        parameterCxv.put("app_id", "6690c7633df0f4b90b4ef551");
        parameterCxv.put("entry_id", "66fa4b35f0b9ba61d818e3a5");
        HashMap<String, String> communti = new HashMap<>();
        communti.put("_widget_1726627883580", purchaseRequest.get_widget_1726627883580());
        communti.put("_widget_1727679387046", purchaseRequest.get_widget_1727679387046());
        List<PurchaseRequest> purchaseRequests = PurchaseCommunity.queryBased(parameterCxv, headers, communti, PurchaseRequest.class);
        if (!purchaseRequests.isEmpty()) {
            purchaseRequests.sort(Comparator.comparing(PurchaseRequest::getCreateTime).reversed());
            if (purchaseRequests.size()>1){
                purchaseRequest.set_widget_1727679387052(purchaseRequests.get(1).get_widget_1727679387052());
            }else {
                purchaseRequest.set_widget_1727679387052(purchaseRequests.getFirst().get_widget_1727679387052());
            }

            for (int i = 1; i < purchaseRequests.size(); i++) {
                Map<String, Object> parameterDelete = new HashMap<>();
                parameterDelete.put("app_id", "6690c7633df0f4b90b4ef551");
                parameterDelete.put("entry_id", "66fa4b35f0b9ba61d818e3a5");
                parameterDelete.put("data_id", purchaseRequests.get(i).get_id());
                String jsonSaleDelete = JSONUtil.toJsonStr(parameterDelete);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/delete", headers, jsonSaleDelete);
            }
        }else {
            return;
        }
        if (purchaseRequest.get_widget_1732525780316() != null) {
            purchaseRequest.set_widget_1732525780316(purchaseRequest.get_widget_1732525780316().toString());
        }
        PurchaseRequest purchaseRequest1 = ConnmeUtils.updateFields(purchaseRequest);
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
        parameterInster.put("entry_id", "66fa4b35f0b9ba61d818e3a5");
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", purchaseRequest1.get_id());
        purchaseRequest1.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(purchaseRequest1));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        log.info("申请单更新的数据{}", jsonSalee);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);

        log.info("采购申请单创建成功");
    }
}
